package com.wisdom.client.cluster.lb;


import com.wisdom.client.cluster.ClientLoadBalanceStrategy;
import com.wisdom.core.annotation.WisdomLoadBalance;
import com.wisdom.core.enums.LoadBalanceStrategy;
import com.wisdom.core.provider.ServiceProvider;
import com.wisdom.core.util.IpUtil;

import java.util.List;

/**
 * @description: <IP哈希负载均衡算法>
 * @author: Leo
 * @date: 2021-08-29 16:43
 */
@WisdomLoadBalance(strategy = LoadBalanceStrategy.HASH)
public class HashClientLoadBalance implements ClientLoadBalanceStrategy {

    @Override
    public ServiceProvider getProvider(List<? extends ServiceProvider> serviceProviders) {
        String realIp = IpUtil.getRealIp();
        int hashCode = realIp.hashCode();
        int i = Math.abs(hashCode % serviceProviders.size());
        return serviceProviders.get(i);
    }

}
